package com.central.apps.handler.contract;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.central.app.common.cache.CfgRedisCache;
import com.central.app.entity.TBFile;
import com.central.app.model.BizApp;
import com.central.app.service.CheckConNodeService;
import com.central.app.service.HandlerService;
import com.central.apps.common.util.FileUtil;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.auth.details.LoginAppUser;
import com.central.common.util.SysUserUtil;
import com.central.common.util.ToolUtil;
import com.central.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2022/9/20.
 */
@Slf4j
@Component
public class ConchangeHandler extends LvBaseHandler {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private FileSynUtilService fileSynUtilService;
    @Autowired
    private CheckConNodeService checkConNodeService;
    @Autowired
    private ConreviewHandler conreviewHandler;
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private CfgRedisCache cfgRedisCache;
    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {


    }

    //根据合同序号便功能
    public void updateStatusByConid(int conid, String status) {
        //修改台账中的合同状态
        String isupdate = "否";
        if (!"变更中".equals(status)) {
            isupdate = "是";

        }
        String sql = "update gq_conaccount set constatus = '" + status + "',isupdate ='" + isupdate + "'  where conid = '" + conid + "'";
        handlerService.updateBySql(sql);
        //合同变更中的合同状态
        String sql6 = "update gq_conchange set constatus = '" + status + "' where conid = '" + conid + "'";
        handlerService.updateBySql(sql6);
        //修改合同申请中的状态
        String sql3 = "update gq_conapplication set constatus = '" + status + "' where conid = '" + conid + "'";
        handlerService.updateBySql(sql3);
        //修改合同评审中的状态
        String sql4 = "update gq_conreviews set constatus = '" + status + "' where conid = '" + conid + "'";
        handlerService.updateBySql(sql4);
        //修改合同签订中的状态
        String sql5 = "update gq_consigns set constatus = '" + status + "' where conid = '" + conid + "'";
        handlerService.updateBySql(sql5);
    }

    //更改合同状态
    public void updateStatus(String concode, String status) {
        //修改台账中的合同状态
        String isupdate = "否";
        if (!"变更中".equals(status)) {
            isupdate = "是";

        }
        String sql = "update gq_conaccount set constatus = '" + status + "',isupdate ='" + isupdate + "'  where concode = '" + concode + "'";
        handlerService.updateBySql(sql);
        //修改合同信息中的合同状态
        String sql2 = "update gq_coninfo set constatus = '" + status + "' where concode = '" + concode + "'";
        handlerService.updateBySql(sql2);
        //合同变更中的合同状态
        String sql6 = "update gq_conchange set constatus = '" + status + "' where concode = '" + concode + "'";
        handlerService.updateBySql(sql6);
        //修改合同申请中的状态
        String sql3 = "update gq_conapplication set constatus = '" + status + "' where concode = '" + concode + "'";
        handlerService.updateBySql(sql3);
        //修改合同评审中的状态
        String sql4 = "update gq_conreviews set constatus = '" + status + "' where concode = '" + concode + "'";
        handlerService.updateBySql(sql4);
        //修改合同签订中的状态
        String sql5 = "update gq_consigns set constatus = '" + status + "' where concode = '" + concode + "'";
        handlerService.updateBySql(sql5);

        String sql7 = "update gq_confinal set constatus = '" + status + "' where concode = '" + concode + "'";
        handlerService.updateBySql(sql7);
        String sql8 = "update gq_conclose set constatus = '" + status + "' where concode = '" + concode + "'";
        handlerService.updateBySql(sql8);
    }

    //更改合同状态By id
    public void updateStatusByid(Long id, String status) {
        //修改合同状态
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("id", id);
            map.put("constatus", status);
            handlerService.update("gq_consigns", map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>> enter ConchangeAfterSaveHandler");
        System.out.println("app :" + app);
        System.out.println("objName :" + objName);
        System.out.println("data :" + JSON.toJSONString(data));
        System.out.println("isUpdate :" + isUpdate);

        //合同变更，选择合同后，将合同中的附件文件显示在变更信息下边
        if ("gq_conchange".equals(objName) && !isUpdate) {
            //获取当前登录人用户名称
            LoginAppUser user = SysUserUtil.getLoginAppUser();
            //部门编码
            String deptcode = user.getDeptcode();
            String username = user.getUsername();
            String deptName = user.getDeptName();
            if (ToolUtil.isEmpty(deptName)) {
                List<Map<String, Object>> deptList = handlerService.findBySql("select fullname from sys_dept where code ='" + deptcode + "'");
                if (CollectionUtils.isNotEmpty(deptList)) {
                    deptName = MapUtils.getString(deptList.get(0), "fullname");
                }
            }
            Long userid = user.getId();

            Long id = MapUtil.getLong(data, "id");
            // 合同编号
            String concode = MapUtil.getStr(data, "concode");
            //合同序号
            String conid = MapUtil.getStr(data, "conid");
            // 合同名称
            String conname = MapUtil.getStr(data, "conname");
            //合同类型
            //String contype = MapUtil.getStr(data, "contype");
            String changeType = (String) data.get("changetype");//变更类型 基础信息，节点信息，合同内容

            if (changeType.contains("合同文本变更")) {
                List<Map<String, Object>> changeList = handlerService.findBySql("select * from tb_file where appname = '" + app + "' and recordid =" + id + "");
                for (int i = 0; i < changeList.size(); i++) {
                    String fileid = MapUtil.getStr(changeList.get(i), "fileid");
                    String pathid = MapUtil.getStr(changeList.get(i), "pathid");
                    String pathname = MapUtil.getStr(changeList.get(i), "filepath");

                    if (StringUtils.isNotBlank(pathid) && StringUtils.isNotBlank(pathname)) {
                        // 删除文件
                        List<Map<String, Object>> pathList = handlerService.findBySql("select * from tb_path where pathid =" + pathid + "");
                        String filepath = MapUtil.getStr(pathList.get(0), "pathname");
                        if (StringUtils.isNotBlank(pathname)) {
                            String[] split = pathname.split("/");
                            pathname = "/" + split[split.length - 1];
                        }
                        String pt = filepath + pathname;
                        new File(pt).delete();
                    }

                    if (StringUtils.isNotBlank(fileid)) {
                        int res1 = checkConNodeService.deleteTbFileLog(fileid);
                        System.out.println(">>>>>>>>>>>>>>>>>>>>>>> TbFileLog 删除状态 : " + res1);
                        int res2 = checkConNodeService.deleteTbFile(fileid);
                        System.out.println(">>>>>>>>>>>>>>>>>>>>>>> TbFile 删除状态 : " + res2);
                    }
                }
                String sql = "";
                //从合同台账中获取合同文本，进行变更，修改后把最新的合同文本附件同步到合同台账
                String appname = "conaccountApp";
                String like = "";
                //合同编号如果为空，从合同申请获取，如果不为空，从合同台账获取
                if (ToolUtil.isEmpty(concode)) {
                    appname = "conapplicationApp";
                    sql = "select id from gq_conapplication where conid ='" + conid + "'";

                } else {
                    sql = "select id from gq_conaccount where conid ='" + conid + "'";
                    like = "  and (filerealname like '%合同申请%'||filerealname like '%合同评审%'  )";
                }
//                if ("专利合同".equals(contype)) {
//                    sql = "select id from gq_conpatent where concode ='" + concode + "'";
//                    appname = "conpatentApp";
//                } else {
//                    sql = "select id from gq_conaccount where conid ='" + conid + "'";
//                }


                //List<Map<String, Object>> templateList = handlerService.findBySql("select * from gq_consigns where concode ='" + concode + "'");
                List<Map<String, Object>> templateList = handlerService.findBySql(sql);
                String tmpId = MapUtil.getStr(templateList.get(0), "id");//合同申请或者合同台账主键id

                List<Map<String, Object>> fileList = handlerService.findBySql("select * from tb_file where isshow=1 and  appname = '" + appname + "' and recordid =" + tmpId + like + " order by statustime desc");

                //取第一个，最新的合同版本
                if (CollectionUtils.isNotEmpty(fileList)) {
                    for (int i = 0; i < 1; i++) {
                        Integer pathid = MapUtil.getInt(fileList.get(i), "pathid");
                        //Date uploadtime = MapUtil.getDate(fileList.get(i), "uploadtime");
                        String filesize = MapUtil.getStr(fileList.get(i), "filesize");
                        String pathname = MapUtil.getStr(fileList.get(i), "filepath");
                        String extensionname = MapUtil.getStr(fileList.get(i), "extensionname");//文件类型
                        //Date statustime = MapUtil.getDate(fileList.get(i), "statustime");
                        //String md5 = MapUtil.getStr(fileList.get(i), "md5");
                        //String secretkey = MapUtil.getStr(fileList.get(i), "secretkey");
                        String filename = MapUtil.getStr(fileList.get(i), "filename");
                        String filerealname = MapUtil.getStr(fileList.get(i), "filerealname");

                        //合同文本变更只变更doc或者docx类型的文件
                        if (!"docx".equals(extensionname) && !"doc".equals(extensionname)) {
                            continue;
                        }
                        List<Map<String, Object>> pathList = handlerService.findBySql("select * from tb_path where pathid =" + pathid + "");
                        String filepath = MapUtil.getStr(pathList.get(0), "pathname");
                        if (StringUtils.isNotBlank(pathname)) {
                            String[] split = pathname.split("/");
                            pathname = "/" + split[split.length - 1];
                        }
                        String pt = filepath + pathname;
                        //
                        InputStream is = new FileInputStream(pt);

                        //XWPFDocument doc = new XWPFDocument(is);
                        String uid = IdUtil.simpleUUID();
                        SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd");
                        String formatNowDate = sdft.format(new Date());
                        String fileName = formatNowDate + "_" + uid + "." + extensionname;
                        //OutputStream os = new FileOutputStream("/home/eam/doclinks/科技发展部/" + fileName);
                        //System.out.println("filepath+fileName"+filepath + fileName);
                        String fileallpath = "/home/eam/doclinks/" + deptName + "/" + fileName;
                        FileUtil.copy(pt, fileallpath);
                        //doc.write(os);
                        //os.close();
                        is.close();

                        // 插入DB
                        TBFile tbFile = new TBFile();
                        //确保tb_path 和tb_file的部门保持一直
                        List<Map<String, Object>> lists = handlerService.findBySql("select pathid from tb_path where foldername='" + deptName + "'");
                        if (CollectionUtils.isNotEmpty(lists)) {
                            pathid = MapUtils.getInteger(lists.get(0), "pathid");
                        }
                        tbFile.setPathid(pathid);
                        if (StringUtils.isNotBlank(deptcode)) {
                            tbFile.setDeptid(deptcode);
                        }
                        if (StringUtils.isNotBlank(deptName)) {
                            tbFile.setDeptfullname(deptName);
                        } else {
                            tbFile.setDeptfullname("科技发展部");
                        }
                        if (userid != null) {
                            tbFile.setUserid(String.valueOf(userid));
                        }
                        if (StringUtils.isNotBlank(username)) {
                            tbFile.setUsername(username);
                        }
                        String fileMd5 = FileUtil.fileMD5(new File(fileallpath));
                        tbFile.setUploadtime(new Date());
                        tbFile.setFilesize(new BigDecimal(filesize));
                        tbFile.setFilepath("/" + deptName + "/" + fileName);
                        tbFile.setExtensionname(extensionname);
                        tbFile.setAppid(499);
                        tbFile.setAppname(app);
                        tbFile.setRecordid(id);
                        tbFile.setFilestatus("已发布");
                        tbFile.setStatustime(new Date());
                        if (StringUtils.isNotBlank(conname)) {
                            tbFile.setFilename(conname);
                            tbFile.setFilerealname(conname + "." + extensionname);
                        } else {
                            tbFile.setFilename(filename);
                            tbFile.setFilerealname(filerealname);
                        }
                        tbFile.setFileversion(1);
                        tbFile.setMd5(fileMd5);
                        tbFile.setSecretkey("");
                        tbFile.setIsshow(1);
                        checkConNodeService.insertConfiles(tbFile);
                    }
                }
            }


            //查询最新的合同节点信息，新增到connode节点表中，在最新的基础上进行变更
            //查询connodenew表，新增到connode表中
            //2.	合同节点执行中的，不允许在进行变更，避免之后的一系列问题   都放出来，避免变更的时候节点数据为空，没办法新增
            List<Map<String, Object>> newList = new ArrayList<>();
            //newList = handlerService.findBySql("select * from gq_connodenew where concode = '" + MapUtils.getString(data, "concode") + "' and status ='未开始'");
            newList = handlerService.findBySql("select * from gq_connodenew where concode = '" + MapUtils.getString(data, "concode") + "' ");
            if (CollectionUtils.isNotEmpty(newList)) {
                //先删除，在增加  当时注释掉了，现在放开了，不知道当时为啥注释掉
                String sql3 = "delete from gq_connode where changecode =" + MapUtils.getString(data, "changecode");
                handlerService.updateBySql(sql3);
                List<Map<String, Object>> codeList = new ArrayList<>();
                for (Map<String, Object> objectMap : newList) {
                    Map<String, Object> objMap = new HashMap<>();
                    objMap.put("nodecode", objectMap.get("nodecode"));
                    objMap.put("nodename", objectMap.get("nodename"));
                    objMap.put("ispaynode", objectMap.get("ispaynode"));
                    objMap.put("nodetype", objectMap.get("nodetype"));
                    objMap.put("starttime", objectMap.get("starttime"));
                    objMap.put("endtime", objectMap.get("endtime"));
                    objMap.put("reviewtime", objectMap.get("reviewtime"));
                    objMap.put("chestandard", objectMap.get("chestandard"));
                    objMap.put("milepostid", objectMap.get("milepostid"));
                    objMap.put("mainpayment", objectMap.get("mainpayment"));
                    objMap.put("receivingamounttax", objectMap.get("receivingamounttax"));
                    objMap.put("receivingamount", objectMap.get("receivingamount"));
                    objMap.put("nid", objectMap.get("id"));
                    objMap.put("changecode", data.get("changecode"));//表更编号从主表中获取
                    objMap.put("concode", data.get("concode"));//合同编号从主表中获取
                    objMap.put("status", objectMap.get("status"));
                    codeList.add(objMap);

                }
                handlerService.batchInsert("conchangeApp", "gq_connode", codeList);
            }


        }
        if ("gq_conchange".equals(objName)) {
            try {
                Long id = MapUtil.getLong(data, "id");

                if ("是".equals(data.get("isonline"))) {
                    System.out.println("当前时间：===插入执行人=========" + new Date());
                    //将主表中的评审意见添加到对应的子表评审意见位置。
                    conreviewHandler.moverevcomments(data);
                    conreviewHandler.setcountersigns(app, id, app);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if ("gq_connodenewbak".equals(objName)) {
            String nodecode = MapUtils.getString(data, "nodecode");
            String changecode = MapUtils.getString(data, "changecode");
            if (ToolUtil.isNotEmpty(nodecode) && ToolUtil.isNotEmpty(changecode)) {
                handlerService.updateBySql("delete from gq_connode where nodecode ='" + nodecode + "' and changecode = '" + changecode + "'");
            }
        }


        super.afterSave(app, objName, data, isUpdate);
    }

    //保存后赋值合同文本公共方法
    public void moveFile(int conid, String appname, String app, long id, String conname) throws FileNotFoundException {
        LoginAppUser user = SysUserUtil.getLoginAppUser();
        //部门编码
        String deptcode = user.getDeptcode();
        String username = user.getUsername();
        String deptName = user.getDeptName();
        if (ToolUtil.isEmpty(deptName)) {
            List<Map<String, Object>> deptList = handlerService.findBySql("select fullname from sys_dept where code ='" + deptcode + "'");
            if (CollectionUtils.isNotEmpty(deptList)) {
                deptName = MapUtils.getString(deptList.get(0), "fullname");
            }
        }
        Long userid = user.getId();
        //List<Map<String, Object>> templateList = handlerService.findBySql("select * from gq_consigns where concode ='" + concode + "'");
        String sql = "select id from gq_conaccount where conid ='" + conid + "'";
        String like = "  and (filerealname like '%合同申请%'||filerealname like '%合同评审%'  )";
        List<Map<String, Object>> templateList = handlerService.findBySql(sql);
        String tmpId = MapUtil.getStr(templateList.get(0), "id");//合同申请或者合同台账主键id

        List<Map<String, Object>> fileList = handlerService.findBySql("select * from tb_file where isshow=1 and  appname = '" + appname + "' and recordid =" + tmpId + like + " order by statustime desc");

        //取第一个，最新的合同版本
        if (CollectionUtils.isNotEmpty(fileList)) {
            for (int i = 0; i < 1; i++) {
                Integer pathid = MapUtil.getInt(fileList.get(i), "pathid");
                //Date uploadtime = MapUtil.getDate(fileList.get(i), "uploadtime");
                String filesize = MapUtil.getStr(fileList.get(i), "filesize");
                String pathname = MapUtil.getStr(fileList.get(i), "filepath");
                String extensionname = MapUtil.getStr(fileList.get(i), "extensionname");//文件类型
                //Date statustime = MapUtil.getDate(fileList.get(i), "statustime");
                //String md5 = MapUtil.getStr(fileList.get(i), "md5");
                //String secretkey = MapUtil.getStr(fileList.get(i), "secretkey");
                String filename = MapUtil.getStr(fileList.get(i), "filename");
                String filerealname = MapUtil.getStr(fileList.get(i), "filerealname");

                //合同文本变更只变更doc或者docx类型的文件
                if (!"docx".equals(extensionname) && !"doc".equals(extensionname)) {
                    continue;
                }
                List<Map<String, Object>> pathList = handlerService.findBySql("select * from tb_path where pathid =" + pathid + "");
                String filepath = MapUtil.getStr(pathList.get(0), "pathname");
                if (StringUtils.isNotBlank(pathname)) {
                    String[] split = pathname.split("/");
                    pathname = "/" + split[split.length - 1];
                }
                String pt = filepath + pathname;
                //
                InputStream is = new FileInputStream(pt);

                //XWPFDocument doc = new XWPFDocument(is);
                String uid = IdUtil.simpleUUID();
                SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd");
                String formatNowDate = sdft.format(new Date());
                String fileName = formatNowDate + "_" + uid + "." + extensionname;
                //OutputStream os = new FileOutputStream("/home/eam/doclinks/科技发展部/" + fileName);
                //System.out.println("filepath+fileName"+filepath + fileName);
                String fileallpath = "/home/eam/doclinks/" + deptName + "/" + fileName;
                FileUtil.copy(pt, fileallpath);
                //doc.write(os);
                //os.close();
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // 插入DB
                TBFile tbFile = new TBFile();
                tbFile.setPathid(pathid);
                if (StringUtils.isNotBlank(deptcode)) {
                    tbFile.setDeptid(deptcode);
                }
                if (StringUtils.isNotBlank(deptName)) {
                    tbFile.setDeptfullname(deptName);
                } else {
                    tbFile.setDeptfullname("科技发展部");
                }
                if (userid != null) {
                    tbFile.setUserid(String.valueOf(userid));
                }
                if (StringUtils.isNotBlank(username)) {
                    tbFile.setUsername(username);
                }
                String fileMd5 = FileUtil.fileMD5(new File(fileallpath));
                tbFile.setUploadtime(new Date());
                tbFile.setFilesize(new BigDecimal(filesize));
                tbFile.setFilepath("/" + deptName + "/" + fileName);
                tbFile.setExtensionname(extensionname);
                BizApp appinfo = cfgRedisCache.getCacheApp(app);
                tbFile.setAppid(appinfo.getId().intValue());
                tbFile.setAppname(app);
                tbFile.setRecordid(id);
                tbFile.setFilestatus("已发布");
                tbFile.setStatustime(new Date());
                if (StringUtils.isNotBlank(conname)) {
                    tbFile.setFilename(conname);
                    tbFile.setFilerealname(conname + "." + extensionname);
                } else {
                    tbFile.setFilename(filename);
                    tbFile.setFilerealname(filerealname);
                }
                tbFile.setFileversion(1);
                tbFile.setMd5(fileMd5);
                tbFile.setSecretkey("");
                tbFile.setIsshow(1);
                checkConNodeService.insertConfiles(tbFile);
            }
        }
    }

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        //
        //提交变更申请后，合同台账和合同信息中的合同状态更改为 变更中
        String createuser = "";
        String deptcode = "";
        String createuserdesc = "";
        if (flowNode.getId().equals("submit1")) {
            //查询接收入库主表gq_conchange
            List<Map<String, Object>> list = handlerService.findBySql("select * from gq_conchange where id=" + id);
            if (CollectionUtils.isNotEmpty(list)) {
                //判断合同金额变动是否超过百分10
                String concode = (String) list.get(0).get("concode");
                String changecode = (String) list.get(0).get("changecode");
                int conid = MapUtils.getIntValue(list.get(0), "conid");
                try {
                    List<Map<String, Object>> list2 = handlerService.findBySql("select paramvalue from gq_pcline where paramcode = 'totalprice'");
                    if (CollectionUtils.isNotEmpty(list2)) {
                        BigDecimal pplinecost = new BigDecimal(MapUtils.getString(list2.get(0), "paramvalue"));//比例
                        //原合同金额
                        List<Map<String, Object>> list3 = null;
                        //如果合同编号为空，从合同申请获取，如果不为空，从合同台账获取
                        if (ToolUtil.isNotEmpty(concode)) {
                            list3 = handlerService.findBySql("select totalprice from gq_consigns where concode = '" + concode + "'");
                        } else {
                            list3 = handlerService.findBySql("select totalprice from gq_conapplication where conid = '" + conid + "'");
                        }

                        BigDecimal totalprice = new BigDecimal(MapUtils.getString(list3.get(0), "totalprice"));//原合同金额
                        System.out.println("totalprice-============" + totalprice);
                        //新合同金额
                        BigDecimal ntotalprice = new BigDecimal(MapUtils.getString(list.get(0), "ntotalprice"));
                        System.out.println("ntotalprice-============" + ntotalprice);
                        //System.out.println("(ntotalprice.subtract(totalprice)).divide(totalprice)-============"+(ntotalprice.subtract(totalprice)).divide(totalprice));
                        BigDecimal tot = (ntotalprice.subtract(totalprice)).divide(totalprice, 2, 2);
                        if (tot.abs().compareTo(pplinecost) == 1) {
                            return "合同的合同变更累计金额不能超出原合同总金额的" + (pplinecost.floatValue() * 100) + "%";
                        }

                    }

                    //判断合同金额是否等于节点累计金额
                    boolean isfra = true;//是否进行节点金额和合同金额的验证
                    String isframecon = MapUtils.getString(list.get(0), "isframecon");//是否是框架合同
                    String ponum = MapUtils.getString(list.get(0), "ponum");
                    if (ToolUtil.isEmpty(isframecon) || "是".equals(isframecon)) {
                        isfra = false;
                    }
                    //采购订单生成的合同，不需要进行金额和节点的验证
                    if (ToolUtil.isNotEmpty(ponum)) {
                        isfra = false;
                    }
                    if (isfra) {
                        String sql5 = "select sum(receivingamounttax) as receivingamounttaxs from  gq_connode where concode = '" + concode + "' and nodetype !='工作节点' and changecode = '" + changecode + "'" +
                                "  and nodecode not in (select nnodecode from gq_connodenewbak where changecode = '" + changecode + "') ";
                        List<Map<String, Object>> list5 = handlerService.findBySql(sql5);
                        BigDecimal receivingamounttaxs = new BigDecimal(0);//原节点金额之和
                        if (CollectionUtils.isNotEmpty(list5) && list5 != null && list5.size() > 0 && ToolUtil.isNotEmpty(list5.get(0))) {
                            receivingamounttaxs = new BigDecimal(MapUtils.getString(list5.get(0), "receivingamounttaxs"));
                        }
                        //合同新金额
                        BigDecimal ntotalprice = new BigDecimal(MapUtils.getString(list.get(0), "ntotalprice"));
                        //新节点金额
                        String sql6 = "select sum(nreceivingamounttax) as nreceivingamounttaxs from  gq_connodenewbak where concode = '" + concode + "' and changecode = '" + changecode + "'";
                        List<Map<String, Object>> list6 = handlerService.findBySql(sql6);
                        BigDecimal nreceivingamounttaxs = new BigDecimal("0");//新节点金额之和
                        if (CollectionUtils.isNotEmpty(list6) && ToolUtil.isNotEmpty(list6.get(0))) {
                            nreceivingamounttaxs = new BigDecimal(MapUtils.getString(list6.get(0), "nreceivingamounttaxs"));
                        }
                        if (ntotalprice.compareTo(receivingamounttaxs.add(nreceivingamounttaxs)) != 0) {
                            return "合同节点金额之和与合同金额不等，请修改合同节点金额";
                        }

                    }


                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    e.printStackTrace();
                    return "提交报错";
                }
                //修改台账中的合同状态 修改合同信息中的合同状态
                if (ToolUtil.isNotEmpty(concode)) {
                    updateStatus(concode, "变更中");
                } else {
                    //合同申请变更，修改合同申请状态
                    handlerService.updateBySql("update gq_conapplication set constatus = '变更中' where conid = " + conid);
                }

                //流程归档
                fileSynUtilService.processarc(app, id + "", "合同变更", (String) list.get(0).get("concode"), (String) list.get(0).get("conname"));
            }
        }
        //将合同评审组成员添加到会签表中
        if (flowNode.getId().equals("approal2")) {
            List<Map<String, Object>> list = handlerService.findBySql("select * from gq_conchange where id=" + id);
            if (CollectionUtils.isNotEmpty(list)) {
                if ("是".equals(list.get(0).get("isonline"))) {
                    //如果是线上评审，需要增加评审人员
                    boolean res = conreviewHandler.isSetPersons(app, id);
                    if (!res) {
                        return "选择线上评审后，需要添加评审组成员信息再提交审批";
                    }
//                    System.out.println("当前时间：===插入执行人========="+new Date());
//                    conreviewHandler.setcountersigns(app, id);
                }
            }
        }
        //会签提交前，验证有没有填写评审意见
        //会签审批通过后，把会签意见同步到意见历史中
        if ("countersign".equals(flowNode.getId())) {
            boolean res = conreviewHandler.isOpinion(app, id);
            if (!res) {
                return "请填写审批意见再提交";
            }
            //conreviewHandler.setRevcoments(app, id);
            //提交会见意见后，置空主表评审意见
            conreviewHandler.setnullrevcomments(id, "gq_conchange");
        }
        if (flowNode.getId().equals("submit3") && op.isFlag()) {
            //gq_conchange
            List<Map<String, Object>> list = handlerService.findBySql("select * from gq_conchange where id=" + id);
            deptcode = MapUtils.getString(list.get(0), "deptcode");
            createuser = MapUtils.getString(list.get(0), "createuser");
            createuserdesc = MapUtils.getString(list.get(0), "createuserdesc");
            //变更历史记录 gq_changeinfo
            if (CollectionUtils.isNotEmpty(list)) {
                //将上传的文件，添加到合同台账里边
                String concode = (String) list.get(0).get("concode");//合同编号
                String oldconstatus = (String) list.get(0).get("oldconstatus");//变更前合同类型
                String conid = (String) list.get(0).get("conid");//合同序号
                String changeType = (String) list.get(0).get("changetype");//变更类型 基础信息，节点信息，合同内容
                String changecode = (String) list.get(0).get("changecode");//变更编号
                System.out.println("concode=================" + concode);
                try {
                    fileSynUtilService.insertFiles(app, id, concode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //新（1）合同变更，跟项目变更风格保持一致
                Map<String, Object> obj = new HashMap<>();
                //查询合同台账表，获取对应的主键id,表更基础内容信息
                String tableName = "gq_conaccount";
                String appname = "conaccountApp";
//                if (ToolUtil.isEmpty(concode)) {
//                    tableName = "gq_conapplication";//合同申请
//                    appname = "conapplicationApp";//合同申请
//                }
                List<Map<String, Object>> conaccountList = handlerService.findBySql("select id from " + tableName + " where conid = '" + conid + "'");
                if (changeType.contains("基础信息变更")) {
                    obj.put("id", conaccountList.get(0).get("id"));
                    obj.put("concode", concode);
                    obj.put("conname", list.get(0).get("nconname"));
                    obj.put("totalprice", list.get(0).get("ntotalprice"));
                    obj.put("nototalprice", list.get(0).get("nnototalprice"));
                    obj.put("maincon", list.get(0).get("nmaincon"));
                    obj.put("isframecon", list.get(0).get("nisframecon"));
                    obj.put("relationprocode", list.get(0).get("nrelationprocode"));
                    obj.put("starttime", list.get(0).get("nstarttime"));
                    obj.put("endtime", list.get(0).get("nendtime"));
                    obj.put("contype", list.get(0).get("ncontype"));
                    obj.put("applicant", list.get(0).get("napplicant"));
                    obj.put("title", list.get(0).get("ntitle"));//标题
                    obj.put("protype", list.get(0).get("nprotype"));//采购方式
                    obj.put("createuser", createuser);
                    obj.put("deptcode", deptcode);
                    obj.put("createuserdesc", createuserdesc);
                    handlerService.update(tableName, obj);
                }
                //合同节点过程表，插入最新的合同节点信
                if (changeType.contains("合同节点变更")) {
                    //新（2）根据变更编号查询新表节点信息，插入到节点变更记录表中
                    List<Map<String, Object>> connodenewList = handlerService.findBySql("select * from gq_connodenewbak where changecode = '" + changecode + "'");
                    if (CollectionUtils.isNotEmpty(connodenewList)) {
                        for (Map<String, Object> objectMap : connodenewList) {
                            //handlerService.insert("gq_connodenewbak", objectMap);
                            //（3）最新的把旧的更新一下  类似于更新了合同台账
                            Map<String, Object> objMap = new HashMap<>();
                            objMap.put("createuser", createuser);
                            objMap.put("deptcode", deptcode);
                            objMap.put("createuserdesc", createuserdesc);
                            if ("变更".equals(objectMap.get("flag"))) {
                                objMap.put("id", objectMap.get("nid"));//connodenew表的主键id
                                //objMap.put("nodecode", objectMap.get("nnodecode"));
                                objMap.put("nodename", objectMap.get("nnodename"));
                                objMap.put("nodetype", objectMap.get("nnodetype"));
                                objMap.put("ispaynode", objectMap.get("nispaynode"));
                                objMap.put("starttime", objectMap.get("nstarttime"));
                                objMap.put("endtime", objectMap.get("nendtime"));
                                objMap.put("reviewtime", objectMap.get("nreviewtime"));
                                objMap.put("chestandard", objectMap.get("nchestandard"));
                                objMap.put("milepostid", objectMap.get("nmilepostid"));
                                objMap.put("mainpayment", objectMap.get("nmainpayment"));
                                objMap.put("receivingamounttax", objectMap.get("nreceivingamounttax"));
                                objMap.put("receivingamount", objectMap.get("nreceivingamount"));
                                objMap.put("changecode", objectMap.get("changecode"));

                                objMap.put("nnodetype", objectMap.get("nnodetype"));
                                objMap.put("nnodename", objectMap.get("nnodename"));
                                objMap.put("nispaynode", objectMap.get("nispaynode"));
                                objMap.put("nstarttime", objectMap.get("nstarttime"));
                                objMap.put("nendtime", objectMap.get("nendtime"));
                                objMap.put("nreviewtime", objectMap.get("nreviewtime"));
                                objMap.put("nchestandard", objectMap.get("nchestandard"));
                                objMap.put("nmilepostid", objectMap.get("nmilepostid"));
                                objMap.put("nmainpayment", objectMap.get("nmainpayment"));
                                objMap.put("nreceivingamounttax", objectMap.get("nreceivingamounttax"));
                                objMap.put("nreceivingamount", objectMap.get("nreceivingamount"));
                                handlerService.update("gq_connodenew", objMap);
                            } else if ("新增".equals(objectMap.get("flag"))) {
                                objMap.put("concode", concode);
                                objMap.put("nodetype", objectMap.get("nnodetype"));
                                objMap.put("nodecode", objectMap.get("nnodecode"));
                                objMap.put("nodename", objectMap.get("nnodename"));
                                objMap.put("ispaynode", objectMap.get("nispaynode"));
                                objMap.put("starttime", objectMap.get("nstarttime"));
                                objMap.put("endtime", objectMap.get("nendtime"));
                                objMap.put("reviewtime", objectMap.get("nreviewtime"));
                                objMap.put("chestandard", objectMap.get("nchestandard"));
                                objMap.put("milepostid", objectMap.get("nmilepostid"));
                                objMap.put("mainpayment", objectMap.get("nmainpayment"));
                                objMap.put("receivingamounttax", objectMap.get("nreceivingamounttax"));
                                objMap.put("receivingamount", objectMap.get("nreceivingamount"));
                                objMap.put("nnodetype", objectMap.get("nnodetype"));
                                objMap.put("nnodename", objectMap.get("nnodename"));
                                objMap.put("nispaynode", objectMap.get("nispaynode"));
                                objMap.put("nstarttime", objectMap.get("nstarttime"));
                                objMap.put("nendtime", objectMap.get("nendtime"));
                                objMap.put("nreviewtime", objectMap.get("nreviewtime"));
                                objMap.put("nchestandard", objectMap.get("nchestandard"));
                                objMap.put("nmilepostid", objectMap.get("nmilepostid"));
                                objMap.put("nmainpayment", objectMap.get("nmainpayment"));
                                objMap.put("nreceivingamounttax", objectMap.get("nreceivingamounttax"));
                                objMap.put("nreceivingamount", objectMap.get("nreceivingamount"));
                                objMap.put("nnodecode", objectMap.get("nnodecode"));
                                objMap.put("changecode", objectMap.get("changecode"));
                                objMap.put("status", "未开始");
                                handlerService.insert("gq_connodenew", objMap);
                            }
                        }
                    }
                }
                if (changeType.contains("合同文本变更")) {
                    //修改台账中的合同状态 修改合同信息中的合同状态
                    //更新合同文本附件，需要更新合同台账，合同签订中的合同文本文件，修改文件路径，
                    //查询合同变更 合同文本对应的那条数据，获取到文件路径，更新到合同台账中对应的合同文件路径
                    //String sql = "select filepath,filerealname  from tb_file where appname = 'conchangeApp' and recordid = "+id +" order by statustime desc ";
                    String sql = "select *  from tb_file where appname = 'conchangeApp' and recordid = " + id + " order by statustime desc ";
                    int version = 2;//合同签订生成合同是V1.0,
                    if (ToolUtil.isNotEmpty(redisUtil.get(conid + app))) {
                        version = (int) redisUtil.get(conid + app) + 1;
                    }
                    List<Map<String, Object>> fileList = handlerService.findBySql(sql);
                    if (CollectionUtils.isNotEmpty(fileList)) {
                        String filePath = (String) fileList.get(0).get("filepath");
                        System.out.println("filepath ===" + filePath);
                        Map<String, Object> map = fileList.get(0);
                        map.put("recordid", conaccountList.get(0).get("id"));
                        map.put("appname", appname);
                        map.put("fileid", "");
                        map.put("filename", map.get("filename") + "_v" + version + ".0");
                        map.put("filerealname", map.get("filename") + "." + map.get("extensionname"));
                        //map.put("filerealname","@版本(" + version + ")"+ map.get("filerealname") );
                        map.put("createuser", createuser);
                        map.put("deptcode", deptcode);
                        map.put("createuserdesc", createuserdesc);
                        handlerService.insert("tb_file", map);
                        redisUtil.set(concode + app, version);
//                            String sql2 = "update tb_file set filepath ='"+filePath+"' where recordid="+conaccountList.get(0).get("id") +" and appname = 'conaccountApp'";
//                            System.out.println("更新语句=========="+sql2);
//                            handlerService.updateBySql(sql2);
                    }
                }
                if (ToolUtil.isNotEmpty(concode)) {
                    if(ToolUtil.isNotEmpty(oldconstatus)){
                        updateStatus(concode, oldconstatus);
                    }else {
                        updateStatus(concode, "执行中");
                    }

                    try {
                        //更新进度条状态
                        fileSynUtilService.updateprocess(concode);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    //合同申请变更，修改合同申请状态
                    handlerService.updateBySql("update gq_conapplication set constatus = '待评审' where conid = " + conid);
                }

            }
        }
        return super.beforeExcuteFlow(app, id, flowNode, op);
    }

    @Override
    public void afterMoveNode(String app, Long id) throws Exception {
        //驳回后同步评审意见到历史评审意见
        conreviewHandler.setAllRevcoments(app, id);
    }
}
